package com.zhuty.aiBioHelper.controller;

import com.zhuty.aiBioHelper.enums.AiRoleType;
import com.zhuty.aiBioHelper.service.AiServiceFactory;
import com.zhuty.aiBioHelper.service.BaseAiService;
import dev.langchain4j.service.Result;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Resource
    private AiServiceFactory aiServiceFactory;

    /**
     * 流式聊天接口
     * 支持通过roleType参数指定AI角色
     * 
     * @param memoryId 会话记忆ID
     * @param message 用户消息
     * @param roleType AI角色类型代码（可选，默认为medical_genetics）
     * @return 流式AI回复
     */
    @GetMapping("/chat")
    public Flux<ServerSentEvent<String>> chat(
            @RequestParam int memoryId, 
            @RequestParam String message,
            @RequestParam(defaultValue = "medical_genetics") String roleType) {
        
        try {
            BaseAiService aiService = aiServiceFactory.getService(roleType);
            return aiService.chatStream(memoryId, message)
                    .map(chunk -> ServerSentEvent.<String>builder()
                            .data(chunk)
                            .build())
                    .onErrorResume(throwable -> 
                            Flux.just(ServerSentEvent.<String>builder()
                                    .data("错误: " + throwable.getMessage())
                                    .build()));
        } catch (Exception e) {
            return Flux.just(ServerSentEvent.<String>builder()
                    .data("服务错误: " + e.getMessage())
                    .build());
        }
    }
    
    /**
     * 同步聊天接口
     * 
     * @param message 用户消息
     * @param roleType AI角色类型代码（可选，默认为medical_genetics）
     * @return AI回复
     */
    @PostMapping("/chat/sync")
    public ResponseEntity<Map<String, Object>> chatSync(
            @RequestParam String message,
            @RequestParam(defaultValue = "medical_genetics") String roleType) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            BaseAiService aiService = aiServiceFactory.getService(roleType);
            String reply = aiService.chat(message);
            
            response.put("success", true);
            response.put("message", reply);
            response.put("roleType", roleType);
            response.put("roleName", AiRoleType.fromCode(roleType).getName());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 带RAG检索增强的聊天接口
     * 
     * @param message 用户消息
     * @param roleType AI角色类型代码（可选，默认为medical_genetics）
     * @return 包含检索内容的AI回复
     */
    @PostMapping("/chat/rag")
    public ResponseEntity<Map<String, Object>> chatWithRag(
            @RequestParam String message,
            @RequestParam(defaultValue = "medical_genetics") String roleType) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            BaseAiService aiService = aiServiceFactory.getService(roleType);
            Result<String> result = aiService.chatWithRag(message);
            
            response.put("success", true);
            response.put("message", result.content());
            response.put("sources", result.sources());
            response.put("roleType", roleType);
            response.put("roleName", AiRoleType.fromCode(roleType).getName());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取所有可用的AI角色类型
     * 
     * @return 可用的AI角色类型列表
     */
    @GetMapping("/roles")
    public ResponseEntity<Map<String, Object>> getAvailableRoles() {
        Map<String, Object> response = new HashMap<>();
        Map<String, Object> roles = new HashMap<>();
        
        for (AiRoleType roleType : AiRoleType.values()) {
            if (aiServiceFactory.isServiceAvailable(roleType)) {
                Map<String, String> roleInfo = new HashMap<>();
                roleInfo.put("code", roleType.getCode());
                roleInfo.put("name", roleType.getName());
                roleInfo.put("description", roleType.getDescription());
                roles.put(roleType.getCode(), roleInfo);
            }
        }
        
        response.put("success", true);
        response.put("roles", roles);
        return ResponseEntity.ok(response);
    }
    
    /**
     * 健康检查接口
     * 
     * @return 服务状态
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> response = new HashMap<>();
        Map<String, Boolean> serviceStatus = new HashMap<>();
        
        for (AiRoleType roleType : AiRoleType.values()) {
            serviceStatus.put(roleType.getCode(), aiServiceFactory.isServiceAvailable(roleType));
        }
        
        response.put("success", true);
        response.put("services", serviceStatus);
        return ResponseEntity.ok(response);
    }
}